package com.longrise.android.loaddata.newloaddata;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;

/**
 * Created by chengsan on 16/5/20.
 */
public class HttpRunnable extends HttpRunnableFather
{

    public HttpRunnable()
    {
    }



    @Override
    public void run()
    {
        InputStream inputStream = null;
        try
        {
            //判断是否设置了加载缓存数据
            if(loadCache)
            {
                resultString = ConfigCache.getUrlCache(url,cacheDic,context,mobileTimeOut,wifiTimeOut);
                if(resultString != null && !resultString.isEmpty())
                {
                    return;
                }

            }

            //1、创建请求对象
            HttpClient httpClient = new DefaultHttpClient();
            if(connectTimeOut > 0)
            {
                //连接超时
                httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,connectTimeOut);
            }

            if(soTimeOut > 0)
            {
                //数据读取超时时间
                httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,soTimeOut);
            }


            //get
            if(requestType == 1)
            {
                HttpGet httpGet = new HttpGet(url);
                if (null != cookID && !cookID.isEmpty())
                {
                    httpGet.addHeader("Cookie",cookID);
                }

                httpResponse = httpClient.execute(httpGet);
            }
            else
            {
                //POST
                HttpPost httpPost = new HttpPost(url);
                if (null != cookID)
                {
                    httpPost.addHeader("Cookie", cookID);
                }
                httpPost.addHeader("App-Version", appVersion);
                httpPost.addHeader("Accept-Encoding","gzip");

                if (map != null)
                {
                    //封装传递参数的集合
                    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                    //往这个集合中添加你要传递的参数
                    for (String key : map.keySet()) {
                        parameters.add(new BasicNameValuePair(key, map.get(key)));
                    }
                    //创建传递参数封装 实体对象
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");
                    //把实体对象存入到httpPost对象中
                    httpPost.setEntity(entity);
                }
                //发送请求
                httpResponse = httpClient.execute(httpPost);
            }


            //判断状态码
            if (200 == httpResponse.getStatusLine().getStatusCode())
            {
                Header[] headers = httpResponse.getHeaders("Content-Encoding");

                //获取Cookid
                getCookies(httpResponse);
                //获取内容
                inputStream = httpResponse.getEntity().getContent();

                boolean isGzip = false;
                // 判断服务器有没有对数据进行gzip压缩
                if(headers.length>0)
                {
                    for (Header header : headers)
                    {
                        if ("gzip".equals(header.getValue()))
                        {
                            isGzip = true;
                            break;
                        }
                    }
                }

                if(isGzip)
                {
                    //如果是压缩过的则解压
                    GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
                    resultString = streamToStr(gzipInputStream);
                }
                else
                {
                    resultString = streamToStr(inputStream);
                }

                if(loadCache)
                {
                    ConfigCache.setUrlCache(resultString,url,cacheDic,context);
                }
            }
        }
        catch (Exception e)
        {
            resultString = null;
        }
        finally
        {

            if(handler != null)
            {
                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        if (null != callBack)
                        {
                            callBack.back(resultString, null, httpResponse,HttpRunnable.this);
                        }
                    }
                });
            }

            if (null != inputStream)
            {
                try
                {
                    inputStream.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 把流对象转换成字符串对象
     *
     * @param is
     * @return
     */
    private String streamToStr(InputStream is)
    {
        try
        {
            // 定义字节数组输出流对象
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            // 定义读取的长度
            int len = 0;
            // 定义读取的缓冲区
            byte buffer[] = new byte[1024];
            // 按照定义的缓冲区进行循环读取，直到读取完毕为止
            while ((len = is.read(buffer)) != -1)
            {
                // 根据读取的长度写入到字节数组输出流对象中
                os.write(buffer, 0, len);
            }
            // 关闭流
            is.close();
            os.close();
            // 把读取的字节数组输出流对象转换成字节数组
            byte data[] = os.toByteArray();
            // 按照指定的编码进行转换成字符串(此编码要与服务端的编码一致就不会出现乱码问题了，android默认的编码为UTF-8)
            return new String(data, "UTF-8");
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取Cookie
     *
     * @param
     */
    private void getCookies(HttpResponse httpResponse)
    {
        org.apache.http.Header[] headers = httpResponse.getHeaders("Set-Cookie");
        if (headers == null)
        {
            return;
        }

        for (int i = 0; i < headers.length; i++)
        {
            String cookie = headers[i].getValue();
            String[] cookievalues = cookie.split(";");
            for (int j = 0; j < cookievalues.length; j++)
            {
                String[] keyPair = cookievalues[j].split("=");
                String key = keyPair[0].trim();
                //String value = keyPair.length > 1 ? keyPair[1].trim() : "";
                if (key != null)
                {
                    int index = key.indexOf("SESSIONID");
                    if (index >= 0)
                    {
                        if(null != this.onCookIDListener)
                        {
                            this.onCookIDListener.onCookID(cookievalues[j]);
                        }
                        return;
                    }

                }
            }
        }
    }
}
